"""CronJob资源Markdown写入器模块"""

from typing import Dict, Any, List
from src.writers.base import Writer
from src.utils.markdown_builder import MarkdownBuilder

class CronJobWriter(Writer):
    """
    CronJob资源Markdown写入器
    负责将提取的CronJob资源信息写入Markdown文件
    """
    
    def write(self, data: Dict[str, Any], output_path: str) -> None:
        """
        将提取的CronJob信息写入Markdown
        
        Args:
            data: 提取的CronJob信息
            output_path: 输出文件路径
        """
        if not data or data.get("kind") != "CronJob":
            self.logger.warning(f"无效的CronJob数据: {data.get('name', '未知')}")
            return
        
        # 创建Markdown构建器
        md = self.create_markdown_builder()
        
        # 收集节标题，用于生成目录
        sections = ["基本信息", "调度信息", "作业配置", "任务模板", "容器"]
        
        # 标题
        md.header(f"CronJob: {data.get('name', '未知')}", 1)
        
        # 命名空间
        md.bold("命名空间:").text(f" {data.get('namespace', 'default')}").newline(2)
        
        # 目录
        if len(sections) > 3:  # 只有当节较多时才添加目录
            md.toc(sections)
        
        # 基本信息
        self._write_basic_info(md, data)
        
        # 调度信息
        self._write_schedule_info(md, data)
        
        # 作业配置
        self._write_job_config(md, data)
        
        # 任务模板
        self._write_job_template(md, data)
        
        # 容器信息
        self._write_containers(md, data)
        
        # 生成Markdown文件
        self.write_markdown(md, output_path)
    
    def _write_basic_info(self, md: MarkdownBuilder, data: Dict[str, Any]) -> None:
        """
        写入基本信息
        
        Args:
            md: Markdown构建器
            data: CronJob数据
        """
        md.header("基本信息", 2)
        
        # 基本元数据表
        basic_info = {
            "名称": data.get("name", ""),
            "命名空间": data.get("namespace", "default"),
            "创建时间": data.get("creation_timestamp", ""),
            "状态": data.get("status", {}).get("phase", "未知")
        }
        
        # 添加最近调度时间（如果有）
        if data.get("status", {}).get("last_schedule_time"):
            basic_info["最近调度时间"] = data.get("status", {}).get("last_schedule_time")
        
        # 添加活跃作业数
        active_jobs_count = len(data.get("status", {}).get("active", []))
        if active_jobs_count > 0:
            basic_info["活跃作业数"] = active_jobs_count
        
        md.dict_table(basic_info)
        
        # 标签和注解
        if data.get("labels"):
            md.header("标签", 3)
            md.dict_table(data.get("labels", {}))
        
        if data.get("annotations"):
            md.header("注解", 3)
            md.dict_table(data.get("annotations", {}))
    
    def _write_schedule_info(self, md: MarkdownBuilder, data: Dict[str, Any]) -> None:
        """
        写入调度信息
        
        Args:
            md: Markdown构建器
            data: CronJob数据
        """
        md.header("调度信息", 2)
        
        schedule_info = {}
        
        # Cron表达式
        schedule = data.get("schedule", "")
        schedule_info["Cron表达式"] = schedule
        
        # 解析Cron表达式
        if schedule:
            try:
                cron_parts = schedule.split()
                if len(cron_parts) == 5:
                    schedule_info["解析"] = f"每{self._parse_cron(schedule)}"
            except Exception:
                pass  # 解析失败时不添加解析信息
        
        # 时区
        if "timezone" in data:
            schedule_info["时区"] = data.get("timezone", "UTC")
        
        # 开始期限秒数
        if "starting_deadline_seconds" in data:
            deadline = data.get("starting_deadline_seconds", 0)
            schedule_info["启动期限"] = f"{deadline}秒"
        
        md.dict_table(schedule_info)
    
    def _parse_cron(self, cron: str) -> str:
        """
        简单解析Cron表达式为可读文本
        
        Args:
            cron: Cron表达式
            
        Returns:
            可读的Cron表达式描述
        """
        parts = cron.split()
        if len(parts) != 5:
            return "无效的Cron表达式"
            
        minute, hour, day_of_month, month, day_of_week = parts
        
        # 简化解释
        if minute == "*":
            minute_text = "每分钟"
        elif "/" in minute:
            base, interval = minute.split("/")
            minute_text = f"每{interval}分钟"
        else:
            minute_text = f"在第{minute}分钟"
            
        if hour == "*":
            hour_text = "每小时"
        elif hour == "0":
            hour_text = "0点"
        else:
            hour_text = f"{hour}点"
            
        if day_of_month == "*" and month == "*" and day_of_week == "*":
            day_text = "每天"
        elif day_of_week != "*":
            day_map = {
                "0": "星期日", "1": "星期一", "2": "星期二", "3": "星期三",
                "4": "星期四", "5": "星期五", "6": "星期六", "7": "星期日"
            }
            if day_of_week in day_map:
                day_text = day_map[day_of_week]
            else:
                day_text = f"每周的第{day_of_week}天"
        else:
            day_text = f"每月{day_of_month}号"
            
        return f"{day_text} {hour_text} {minute_text} 执行"
    
    def _write_job_config(self, md: MarkdownBuilder, data: Dict[str, Any]) -> None:
        """
        写入作业配置信息
        
        Args:
            md: Markdown构建器
            data: CronJob数据
        """
        md.header("作业配置", 2)
        
        job_config = {}
        
        # 并发策略
        concurrency_policy = data.get("concurrency_policy", "")
        if concurrency_policy:
            policy_map = {
                "Allow": "允许并发执行",
                "Forbid": "禁止并发执行，跳过新作业",
                "Replace": "替换现有作业"
            }
            job_config["并发策略"] = policy_map.get(concurrency_policy, concurrency_policy)
        
        # 历史限制
        if "successful_jobs_history_limit" in data:
            job_config["成功作业历史限制"] = data.get("successful_jobs_history_limit", 3)
            
        if "failed_jobs_history_limit" in data:
            job_config["失败作业历史限制"] = data.get("failed_jobs_history_limit", 1)
        
        # 作业暂停
        job_config["暂停"] = "是" if data.get("suspend", False) else "否"
        
        md.dict_table(job_config)
    
    def _write_job_template(self, md: MarkdownBuilder, data: Dict[str, Any]) -> None:
        """
        写入Job模板信息
        
        Args:
            md: Markdown构建器
            data: CronJob数据
        """
        md.header("任务模板", 2)
        
        job_template = data.get("job_template", {})
        if not job_template:
            md.paragraph("未定义任务模板")
            return
            
        job_spec = job_template.get("spec", {})
        if not job_spec:
            md.paragraph("任务模板中未定义规格")
            return
            
        template_info = {}
        
        # 完成期限
        if "active_deadline_seconds" in job_spec:
            deadline = job_spec.get("active_deadline_seconds", 0)
            template_info["完成期限"] = f"{deadline}秒"
            
        # 重试次数
        if "backoff_limit" in job_spec:
            template_info["重试次数"] = job_spec.get("backoff_limit", 6)
            
        # 并行度
        if "parallelism" in job_spec:
            template_info["并行Pod数"] = job_spec.get("parallelism", 1)
            
        # 完成数量
        if "completions" in job_spec:
            template_info["需要完成的Pod数"] = job_spec.get("completions", 1)
            
        # 失败重启策略
        pod_spec = job_spec.get("template", {}).get("spec", {})
        if "restart_policy" in pod_spec:
            policy = pod_spec.get("restart_policy", "")
            policy_map = {
                "Never": "永不重启",
                "OnFailure": "失败时重启",
                "Always": "总是重启"
            }
            template_info["重启策略"] = policy_map.get(policy, policy)
        
        md.dict_table(template_info)
    
    def _write_containers(self, md: MarkdownBuilder, data: Dict[str, Any]) -> None:
        """
        写入容器信息
        
        Args:
            md: Markdown构建器
            data: CronJob数据
        """
        md.header("容器", 2)
        
        # 获取容器信息
        pod_spec = data.get("job_template", {}).get("spec", {}).get("template", {}).get("spec", {})
        containers = pod_spec.get("containers", [])
        
        if not containers:
            md.paragraph("未定义容器")
            return
        
        # 遍历每个容器
        for i, container in enumerate(containers):
            container_name = container.get("name", f"container-{i+1}")
            md.header(f"容器 {i+1}: {container_name}", 3)
            
            # 基本容器信息
            with md.list() as lst:
                lst.item(f"**镜像:** {container.get('image', '未指定')}")
                
                if "image_pull_policy" in container:
                    lst.item(f"**镜像拉取策略:** {container.get('image_pull_policy')}")
                    
                if "command" in container:
                    command = " ".join(container.get("command", []))
                    lst.item(f"**命令:** `{command}`")
                    
                if "args" in container:
                    args = " ".join(container.get("args", []))
                    lst.item(f"**参数:** `{args}`")
            
            # 环境变量
            if "env" in container:
                self._write_env_vars(md, container.get("env", []))
                
            # 资源限制
            if "resources" in container:
                self._write_resources(md, container.get("resources", {}))
            
            # 卷挂载
            if "volume_mounts" in container:
                self._write_volume_mounts(md, container.get("volume_mounts", []))
    
    def _write_env_vars(self, md: MarkdownBuilder, env_vars: List[Dict[str, Any]]) -> None:
        """
        写入环境变量信息
        
        Args:
            md: Markdown构建器
            env_vars: 环境变量列表
        """
        if not env_vars:
            return
            
        md.header("环境变量", 4)
        
        headers = ["名称", "值", "来源"]
        rows = []
        
        for env in env_vars:
            name = env.get("name", "")
            value = env.get("value", "")
            value_from = ""
            
            if "value_from" in env:
                value_from_dict = env.get("value_from", {})
                if "configMapKeyRef" in value_from_dict:
                    cm_ref = value_from_dict.get("configMapKeyRef", {})
                    value_from = f"ConfigMap: {cm_ref.get('name', '')}.{cm_ref.get('key', '')}"
                elif "secretKeyRef" in value_from_dict:
                    secret_ref = value_from_dict.get("secretKeyRef", {})
                    value_from = f"Secret: {secret_ref.get('name', '')}.{secret_ref.get('key', '')}"
                elif "fieldRef" in value_from_dict:
                    field_ref = value_from_dict.get("fieldRef", {})
                    value_from = f"Field: {field_ref.get('field_path', '')}"
            
            rows.append([name, value, value_from])
        
        md.table(headers, rows)
    
    def _write_resources(self, md: MarkdownBuilder, resources: Dict[str, Any]) -> None:
        """
        写入资源限制信息
        
        Args:
            md: Markdown构建器
            resources: 资源限制字典
        """
        if not resources:
            return
            
        md.header("资源配置", 4)
        
        if "requests" in resources:
            md.bold("请求:").newline()
            
            with md.list() as lst:
                for resource_type, value in resources.get("requests", {}).items():
                    lst.item(f"{resource_type}: {value}")
            
            md.newline()
        
        if "limits" in resources:
            md.bold("限制:").newline()
            
            with md.list() as lst:
                for resource_type, value in resources.get("limits", {}).items():
                    lst.item(f"{resource_type}: {value}")
            
            md.newline()
    
    def _write_volume_mounts(self, md: MarkdownBuilder, volume_mounts: List[Dict[str, Any]]) -> None:
        """
        写入卷挂载信息
        
        Args:
            md: Markdown构建器
            volume_mounts: 卷挂载列表
        """
        if not volume_mounts:
            return
            
        md.header("卷挂载", 4)
        
        headers = ["名称", "挂载路径", "只读"]
        rows = []
        
        for mount in volume_mounts:
            name = mount.get("name", "")
            path = mount.get("mount_path", "")
            read_only = "是" if mount.get("read_only", False) else "否"
            
            rows.append([name, path, read_only])
        
        md.table(headers, rows)